package it.tic.sbibm.persistence;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class IbatisPersistenceAccess {

	private static SqlSessionFactory sqlSessionFactory = null;
	
	public static synchronized SqlSession getMySqlServerSqlSession() {
		return IbatisPersistenceAccess.getSqlSession("IbatisConfigurationMysql.xml");
	}
	
	public static synchronized SqlSession getSqlSession(String configFilePath) {
		SqlSession sqlSession = null;
		
		if (sqlSessionFactory == null) {
			try {
				Reader reader = Resources.getResourceAsReader(configFilePath);
				SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
				sqlSessionFactory = sfb.build(reader);
			} catch (IOException ex) {
				ex.printStackTrace();
				return null;
			}
		}
		// TODO: disable auto commit and manage with container
		sqlSession = sqlSessionFactory.openSession(true);
		//sqlSession = sqlSessionFactory.openSession();
		return sqlSession;
	}
	
}
